<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书评网</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0,user-scalable=no">
    <!-- 引入样式文件 -->
    <link
            rel="stylesheet"
            href="/assets/vant/index.css"
    />

    <!-- 引入 Vue 和 Vant 的 JS 文件 -->
    <script src="/assets/vue/vue.global.js"></script>
    <script src="/assets/vant/vant.min.js"></script>
    <script src="/assets/axios/axios.js"></script>
    <style>
        .description {
            padding: 5px;
        }

        .description p {
            text-indent: 2em;
            line-height: 30px;
        }

        .description img {
            width: 100%;
        }
    </style>
</head>
<body>
<div id="app">
    <!--导航栏 -->
    <van-nav-bar @click-right="clickRight">
        <template #left>
            <a href="/" style="padding-top: 10px">
                <img src="/images/logo2.png" style="width: 80px">
            </a>
        </template>
        <template #right>
            <template v-if = "state.isLogin">
                <img src="/images/user_icon2.png" style="height:30px">{{state.member.nickname}}
            </template>
            <template v-if = "!state.isLogin">
                <img src="/images/user_icon.png" style="height: 30px">
                登录
            </template>

        </template>
    </van-nav-bar>

    <van-row style="padding: 10px;color:white;font-size: 80%;background: rgb(127, 125, 121)">
        <van-col span="8" style="float: left;width: 110px;height: 160px">
            <img style="width: 110px;height: 160px"
                 :src="book.cover">
        </van-col>
        <van-col span="16" style="float: left;height: 160px;width:auto">
            <div style="font-size: 16px;font-weight: bold">{{book.bookName}}</div>
            <div style="margin-top:5px;background: #92B8B1;padding: 5px">{{book.author}}</div>
            <div style="font-size: 16px;margin-top:5px;">{{book.subTitle}}</div>

            <div style="padding:10px">
                <template v-if="state.readState == -1">
                    <van-button size="small" icon="like-o" type="default" style="margin-right: 10px" @click="updateReadState(1)">想看</van-button>
                    <van-button size="small" icon="passed" type="default" @click="updateReadState(2)">看过</van-button>
                </template>
                <template v-if="state.readState == 1">
                    <van-button size="small" icon="like-o" type="success" style="margin-right: 10px" @click="updateReadState(1)">想看</van-button>
                    <van-button size="small" icon="passed" type="default" @click="updateReadState(2)">看过</van-button>
                </template>

                <template v-if="state.readState == 2">
                    <van-button size="small" icon="like-o" type="default" style="margin-right: 10px" @click="updateReadState(1)">想看</van-button>
                    <van-button size="small" icon="checked" type="success" @click="updateReadState(2)">看过</van-button>
                </template>
            </div>
        </van-col>
        <van-col span="24" style="background-color: rgba(0,0,0,0.1);padding: 10px;margin-top: 10px">
            <span style="line-height: 20px;margin-right: 10px">{{book.evaluationScore}}分 {{book.evaluationQuantity}}人已评</span>
            <van-rate v-model="book.evaluationScore" color="#ffd21e" void-icon="star" readonly allow-half></van-rate>
        </van-col>
    </van-row>
    <div class="description" v-html="book.description"></div>

    <!--短评开始-->
    <van-nav-bar style="background: lightblue">
        <template #left>
            短评
        </template>
        <template #right>
            <van-button type="success" size="small" style="width:60px" @click="showDialog()">评价</van-button>
        </template>
    </van-nav-bar>

    <!--遍历短评列表-->
    <template v-for="(evaluation,index) in evaluationList">
    <div style="border-bottom: 1px solid #cccccc">
        <div style="padding: 10px;">
            <span style="margin-right: 20px">{{evaluation.createTime}}</span>
            <span style="margin-right: 20px">{{evaluation.nickname}}</span>
            <van-rate v-model="evaluation.score" color="#ffd21e" void-icon="star" readonly allow-half></van-rate>
            <van-button icon="like-o" @click="enjoy(index)" type="success" size="small" style="width:40px;float:right" >{{evaluation.enjoy}}</van-button>
        </div>
        <div style="padding: 10px;">
            {{evaluation.content}}
        </div>
    </div>
    </template>

    <div style="margin-bottom: 50px">
    </div>

    <!--点击评价跳出来的框-->
    <van-action-sheet v-model:show="state.dialogVisible" :title="book.bookName">
        <van-form ref="evaluationForm">
            <van-cell-group inset>
                <van-rate v-model="form.score" color="#ffd21e" void-icon="star" style="padding: 16px" ></van-rate>
                <van-field
                        v-model="form.content"
                        name="content"
                        placeholder="这里输入评论内容"
                        autocomplete = "off"
                        :rules="[{ required: true, message: '请输入评论内容' }]"
                />
            </van-cell-group>
            <div style="margin: 16px;margin-bottom: 50px">
                <van-button round block type="primary" @click="onSubmit('evaluationForm')">
                    提交短评
                </van-button>
            </div>
        </van-form>
    </van-action-sheet>

</div>
<script>
    //日期格式化函数,把时间戳变为日期类型
    function formatDate(time){
        var newDate = new Date(time);
        return newDate.getFullYear()+"-"+(newDate.getMonth() + 1) + "-" + newDate.getDate();
    }
    //获取查询字符串函数
    function getQueryString() {
        /*window.location.search得到？及后面的字符串*/
        var r = window.location.search.match("[0-9]+");
        if (r != null) {
            return r;
        }
        return null;
    }
    //提示"需要登录"对话框
    function warnLogin(text){
        vant.Dialog.confirm({
            title: text,
            confirmButtonText: "去登录",
            cancelButtonText: "关闭"
        })
        .then(() => {
            window.location.href = "/login.html";
        })
    }

    const main = {
        data() {
            return {
                state : { //页面状态
                    isLogin: false, //是否登录
                    member:{}, //当前登录会员数据
                    readState : -1, //当前会员阅读状态 -1:无数据 1:想看 2:看过
                    dialogVisible : false //短评对话框是否显示
                },
                book: { //图书数据
                    "bookId": 5,
                    "bookName": "从 0 开始学爬虫",
                    "subTitle": "零基础开始到大规模爬虫实战",
                    "author": "梁睿坤 · 19年资深架构师",
                    "cover": "/images/5ce256ea00014bc903600480.jpg",
                    "description": "...",
                    "categoryId": 2,
                    "evaluationScore": 4.9,
                    "evaluationQuantity": 15
                },
                evaluationList:[], //短评列表
                form: { //短评表单数据
                    score:5,
                    content:""
                }
            }
        }
        , methods: {
            //对短评列表进行封装
            showEvaluationList:function (bookId,isFlush) {
                const objApp=this;
                /*2.请求得到对应书本的短评列表*/
                var uri="/evaluation/list?bookId="+bookId;
                axios.get(uri).then(function (resp){
                    const json = resp.data;
                    if (json.code==10000){
                        /*是否清空原有的短评*/
                        if (isFlush){
                            objApp.evaluationList.splice(0,objApp.evaluationList.length);
                        }
                        const list = json.data;
                        list.forEach(function (item){
                            //把时间戳转换成自定义日期格式
                            item.createTime=formatDate(item.createTime);
                            //绑定到对象中
                            objApp.evaluationList.push(item);
                        });
                    } else {
                        /*数据错误，在控制台中打印*/
                        console.error(json);
                    }
                });
            },

            //显示短评对话框
            showDialog:function(){
                const objApp = this;
                if(!objApp.state.isLogin){
                    warnLogin("登录后才能进行评论哦");
                    return;
                }
                this.state.dialogVisible = true;
            }
            ,clickRight:function(){
                //点击"登录"按钮跳转到登录页
                if(!this.state.isLogin){
                    window.location.href = "/login.html";
                }
            }
            ,updateReadState:function(readState){
                //更新阅读状态
                const objApp=this;
                //获取当前的会员编号及书本编号
                const memberId=sessionStorage.mid;
                const bookId = window.location.search.match("[0-9]+");

                /*判断是否登录*/
                if (!objApp.state.isLogin){
                    //没登陆，提示其登录
                    warnLogin("请登录");
                    return;
                }
                /*创建参数对象*/
                const params = new URLSearchParams();
                params.append("memberId",memberId);
                params.append("bookId",bookId);
                params.append("readState",readState);
                axios.post("/member/update_read_state",params).then(function (resp){
                    const json=resp.data;
                    if (json.code==10000){
                        //更新状态
                        objApp.state.readState=json.data.readState;
                    }else {
                        console.error(json);
                    }
                })


            }
            ,onSubmit: function (formName) {
                //提交短评功能
                const objApp=this;
                //获取表单对象
                const form=objApp.$refs[formName];
                //获取会员编号和书本id
                const memberId=sessionStorage.mid;
                /*window.location.search得到？及后面的字符串,match("[0-9]+")只保留数字*/
                const bookId = window.location.search.match("[0-9]+");

                //先进行表单的校验，再执行请求
                form.validate().then(function (){
                    /*实例化参数对象*/
                    const params = new URLSearchParams();
                    params.append("memberId",memberId);
                    params.append("bookId",bookId);
                    params.append("score",objApp.form.score);
                    params.append("content",objApp.form.content);
                    axios.post("/evaluation/evaluate",params).then(function (resp){
                        const json=resp.data;
                        if (json.code==10000){
                            /*1.恢复表单的初始化*/
                            objApp.state.dialogVisible=false;
                            objApp.form.score=5;
                            objApp.form.content="";
                            /*刷新短评列表（重新查询短评列表。。。）*/
                            objApp.showEvaluationList(bookId,true);
                        }else {
                            console.error(json);
                        }
                    })
                }).catch(function (e){
                    console.debug("表单验证失败",e);
                })
            }
            ,enjoy : function(index){
                //点赞功能
                const objApp=this;
                const memberId=sessionStorage.mid;
                if (!objApp.state.isLogin){
                    //没登陆，提示其登录
                    warnLogin("请登录");
                    return;
                }
                //得到对应的短评
                const evaluation = objApp.evaluationList[index];
                const params = new URLSearchParams();
                params.append("evaluationId",evaluation.evaluationId);
                axios.post("/evaluation/enjoy",params).then(function (resp){
                    const json = resp.data;
                    if (json.code==10000){
                        //更新点赞数
                        evaluation.enjoy=json.data.enjoy;
                    }else {
                        console.error(json)
                    }
                })
            }
        }
        , mounted() {
            //初始化后数据操作
            const objApp=this;

            /*1.请求得到对应的书本详情*/
            // const bookId=getQueryString();
            /*window.location.search得到？及后面的字符串,match("[0-9]+")只保留数字*/
            var bookId = window.location.search.match("[0-9]+");

            var uri="/book/detail?bookId="+bookId;
            axios.get(uri).then(function (resp){
                const json=resp.data;
                if (json.code==10000){
                    /*动态绑定*/
                    objApp.book=json.data;
                }else {
                    /*数据错误，在控制台中打印*/
                    console.error(json);
                }
            });


            /*2. 查询短评列表*/
            objApp.showEvaluationList(bookId,false);

            /*判断是否已登陆*/
            const mid=sessionStorage.mid; //登录是存储的
            if (mid!=null){
                /*已登录，查询登录者信息*/
                axios.get("/member/select_by_id?memberId="+mid).then(function (resp){
                    const json=resp.data;
                    if (json.code==10000){
                        //已登录
                        objApp.state.isLogin=true;
                        //赋值
                        objApp.state.member=json.data;
                    }else {
                        console.error(json);
                    }
                });

                /*在判断已登录的状态中查找会员的阅读状态*/
                var uri="/member/select_member_read_state?memberId="+mid+"&bookId="+bookId;
                axios.get(uri).then(function (resp){
                    const json=resp.data;
                    if (json.code==10000){
                        if (json.data!=null){
                            /*数据库中有数据*/
                            objApp.state.readState=json.data.readState;
                        }else {
                            /*数据库中无数据*/
                            objApp.state.readState=-1;
                        }
                    }else {
                        console.error(json);
                    }
                })

            }

        }
    };
    const app = Vue.createApp(main);
    app.use(vant);
    app.use(vant.Lazyload);
    app.mount("#app");
</script>
</body>
</html>